/*
 * @Author: hc
 * @Date: 2023-10-10 14:04:55
 * @LastEditTime: 2023-10-13 10:56:16
 * @LastEditors: hc
 * @Description:
 */
import React from 'react';
import { getCurrentWindow, udp } from '@cscec/udp-ui';
import { ContextMenu, ThemedContextMenu } from 'amis-ui/lib/components/ContextMenu';
import ReactDOM from 'react-dom';
import { createRoot } from 'react-dom/client';

/**
 * 集成到qiankun微前端架构时，需要重写部分函数
 */
const global = getCurrentWindow();

if (udp.isRunMaster) {
  // amis 内部js加载路径重写，保证打包后路径正确获取
  if (global.MonacoEnvironment) {
    const { getWorkerUrl } = global.MonacoEnvironment;
    global.MonacoEnvironment.getWorkerUrl = (moduleId: string, label: string) => {
      const url = udp.getPublicPath(getWorkerUrl(moduleId, label));
      return url;
    };
  }

  // context菜单
  ContextMenu.getInstance = async () => {
    const name = udp.external.getQianKun?.().name;
    if (!ContextMenu.instance) {
      const container = document.body.querySelector(`div[data-qiankun="${name}"]`) || document.body;
      const div = document.createElement('div');
      const root = createRoot(div);
      container.appendChild(div);
      root.render(<ThemedContextMenu />);
    }

    return ContextMenu.instance;
  };

  // 解决子应用的模态框挂载到body下导致样式丢失的问题
  const oldCreatePortal = ReactDOM.createPortal;
  ReactDOM.createPortal = (children, container, key) => {
    if (container === document.body) {
      const name = udp.external.getQianKun?.().name;
      const nameContainer = document.body.querySelector(`div[data-qiankun="${name}"]`) || container;
      return oldCreatePortal(children, nameContainer, key);
    }
    return oldCreatePortal(children, container, key);
  };
}
